# 认证组件（登录认证）

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from common.response_code import ResponseCode
from user.models import User


# 登录认证
class LoginAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get("HTTP_AUTHORIZATION")

        if not token:
            return None

        token = token.split("Bearer ")[1]
        
        user = User.objects.filter(token = token).first()

        if not user:
            raise AuthenticationFailed({"code": ResponseCode.AUTHENTICATION_INVALID.value[0],
                                        "message": ResponseCode.AUTHENTICATION_INVALID.value[1]})

        return user, token

    def authenticate_header(self, request):
        return "请先登录"


# 请求中没有带token
class NoLoginAuthentication(BaseAuthentication):
    def authenticate(self, request):
        return None

    def authenticate_header(self, request):
        return "您已登录"
